<?php

namespace App\Trip\Passengers;

use App\Models\Passengers\Passenger;
use App\Trip\Tencent\Cloud\Market\IdCard\IdCheckPost;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class PassengerCheck
{
    private string $truename;
    private string $identity_code;
    private string $id_name_key;
    private string $id_key;

    /**
     * @throws Exception
     */
    public function __construct(string $identity_code, string $truename)
    {
        $this->id_name_key   = "PassengerCheck:{$identity_code}:{$truename}";
        $this->id_key        = "PassengerCheck:{$identity_code}";
        $this->truename      = $truename;
        $this->identity_code = $identity_code;
        $this->checkIdentityCodeName();
    }

    /**
     * @throws Exception
     */
    private function checkIdentityCodeName(): void
    {
        $correct_name = $this->getIdentityCodeName();
        if ($correct_name && $correct_name != $this->truename) {
            Log::error("身份证号或姓名填写错误,{$this->identity_code},{$correct_name},{$this->truename}");
            throw new Exception("身份证号或姓名填写错误");
        }
    }

    public function getIdentityCodeName(): string
    {
        if (!Redis::exists($this->id_key)) {
            Log::info("PassengerCheck:getIdentityCodeName:{$this->identity_code}-{$this->truename},无缓存");
            return '';
        }
        return Redis::hget($this->id_key, 'truename');
    }

    public function getIdentityCode(): string
    {
        return $this->identity_code;
    }

    /**
     *  0 锁   1 成功   3 失败
     *
     * @throws GuzzleException
     */
    public function goCheck(): int
    {
        $key = "PassengerCheck:goCheck:{$this->identity_code}-{$this->truename}";
        // 如果核验名称存在
        if ($this->getIdentityCodeName()) {
            $ret = $this->getIdentityCodeName() == $this->truename ? Passenger::VERIFY_STATE_VERIFIED : Passenger::VERIFY_STATE_FAILED;
            Log::info("{$key}:证件已核验的姓名存在,匹配结果:{$ret}");
            return $ret;
        }

        $idCheckPost = new IdCheckPost($this->identity_code, $this->truename);
        try {
            $checkRes = $idCheckPost->query();
            if ($checkRes->isPassCheck()) {
                Redis::set($this->id_name_key, 1);
                Redis::hset($this->id_key, 'truename', $this->truename);
                Log::info("{$key}:核验成功");
                return Passenger::VERIFY_STATE_VERIFIED;
            } else {
                Log::info("{$key}:核验失败");
                return Passenger::VERIFY_STATE_FAILED;
            }
        } catch (Exception $e) {
            Log::info("{$key}:核验失败,外部程序异常,{$e->getMessage()}");
            return 0;
        }

    }


}